package zxq.rollcall.course.aspect;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import zxq.rollcall.course.entity.dto.ResultDTO;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Aspect
@Component
public class WebExceptionAspect {

    private Exception e;

    //凡是注解了RequestMapping的方法都被拦截
    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    private void webPointcut() {
    }
    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
    private void postPointcut() {
    }
    @Pointcut("execution(* zxq.rollcall.course..*.*(..))")
    private void bountyHunterPointcut() {
    }

    @Before("bountyHunterPointcut()")
    public void beforeLog(JoinPoint joinPoint){
        log.info("我是前置通知"+joinPoint.getSignature().getName());
    }
    /**
     * 拦截web层异常，记录异常日志，并返回友好信息到前端 目前只拦截Exception，是否要拦截Error需再做考虑
     *
     * @param e
     *            异常对象
     */
    @AfterThrowing(pointcut = "bountyHunterPointcut()", throwing = "e")
    public void handleThrowing(JoinPoint joinPoint,Exception e) {
        this.e = e;
        //e.printStackTrace();
        log.error("发现异常！" + e.getMessage());
        //log.error(JSON.toJSONString(e.getStackTrace()));
        //这里输入友好性信息
        writeContent("出现异常" + e.getMessage());
    }

    /**
     * 将内容输出到浏览器
     *
     * @param content
     *            输出内容
     */
    private void writeContent(String content) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getResponse();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "text/json;charset=UTF-8");
        response.setHeader("icop-content-type", "exception");
        PrintWriter writer = null;
        JsonGenerator jsonGenerator = null;
        try {
            writer = response.getWriter();
            jsonGenerator = (new ObjectMapper()).getFactory().createGenerator(writer);
            ResultDTO resultDTO = new ResultDTO<>(-1,content,null);
            jsonGenerator.writeObject(resultDTO);
        } catch (IOException e1) {
            e1.printStackTrace();
        }finally {
            writer.flush();
            writer.close();
        }
    }


}
